package org.klaoye.musicplayer;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;

import androidx.annotation.RequiresApi;

import org.klaoye.musicplayer.bean.ReceiverStrings;

import java.util.Objects;

public class MyNotificationBuilder extends Notification.Builder implements ReceiverStrings {
    Context context;
    RemoteViews views;
    BroadcastReceiver receiver;

    @RequiresApi(api = Build.VERSION_CODES.O)
    public MyNotificationBuilder(Context context, String channel) {
        super(context, channel);
        this.context = context;
        buildView();
    }

    public MyNotificationBuilder(Context context) {
        super(context);
        this.context = context;
        buildView();
    }

    private void buildView() {
        views = new RemoteViews(context.getPackageName(), R.layout.player_notification);
        receiver = createReceiver();
        IntentFilter filter = new IntentFilter(BROADCAST_SERVICE);
        context.registerReceiver(receiver, filter);
        int[] flags = {PLAY, LAST, NEXT};
        int[] viewIds = {R.id.img_btn_notification_play, R.id.img_btn_notification_last, R.id.img_btn_notification_next};
        for (int i = 0; i < flags.length; i++) {
            Intent intent = new Intent(BROADCAST_NOTIFICATION).putExtra(FLAG_INT, flags[i]);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, flags[i], intent, PendingIntent.FLAG_CANCEL_CURRENT);
            views.setOnClickPendingIntent(viewIds[i], pendingIntent);
        }

        setSmallIcon(R.drawable.music);
        setContent(views);
    }

    private BroadcastReceiver createReceiver() {
        return new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String s = intent.getStringExtra(FLAG_STRING);
                views.setTextViewText(R.id.textView_notify_tittle, s);
                NotificationManager m = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                m.notify(12, MyNotificationBuilder.this.build());
                Log.i("GetReceive", s);
            }
        };
    }
}
